package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.VolunteerDTO;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.entity.VolunteerInfo;
import com.tju.ocean_ecology_website.mapper.UserMapper;
import com.tju.ocean_ecology_website.service.UserService;
import com.tju.ocean_ecology_website.service.VolunteerInfoService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;

/**
 * 志愿者个人资料控制器
 */
@RestController
@RequestMapping("/api/volunteer")
public class VolunteerProfileController {

    @Resource
    private UserService userService;

    @Resource
    private VolunteerInfoService volunteerInfoService;

    @Resource
    private UserMapper userMapper;

    /**
     * 获取志愿者个人资料
     *
     * @return 志愿者个人资料
     */
    @GetMapping("/profile")
    public ResponseEntity<ApiResponse<VolunteerDTO>> getVolunteerProfile() {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询用户数据
        User user = userService.queryById(currentUserId);
        if (user == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "用户不存在"));
        }

        // 查询志愿者信息
        VolunteerInfo volunteerQuery = new VolunteerInfo();
        volunteerQuery.setUserId(currentUserId);
        Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(volunteerQuery, PageRequest.of(0, 1));
        VolunteerInfo volunteerInfo = volunteerInfoPage.isEmpty() ? new VolunteerInfo() : volunteerInfoPage.getContent().get(0);

        // 构建DTO
        VolunteerDTO dto = VolunteerDTO.fromUserAndVolunteerInfo(user, volunteerInfo);

        return ResponseEntity.ok(ApiResponse.success(dto));
    }

    /**
     * 更新志愿者个人资料
     *
     * @param volunteerDTO 志愿者信息
     * @return 更新结果
     */
    @PutMapping("/profile")
    public ResponseEntity<ApiResponse<VolunteerDTO>> updateVolunteerProfile(@RequestBody VolunteerDTO volunteerDTO) {
        try {
            // 获取当前用户ID
            Long currentUserId = getCurrentUserId();

            // 查询用户数据
            User user = userService.queryById(currentUserId);
            if (user == null) {
                return ResponseEntity.badRequest().body(ApiResponse.error(400, "用户不存在"));
            }

            // 更新用户信息
            user.setName(volunteerDTO.getName());
            user.setEmail(volunteerDTO.getEmail());
            user.setPhone(volunteerDTO.getPhone());
            if (volunteerDTO.getAvatar() != null) {
                user.setAvatar(volunteerDTO.getAvatar());
            }
            user.setUpdateTime(new Date());

            User updatedUser = userService.update(user);

            // 查询志愿者信息
            VolunteerInfo volunteerInfo = null;
            VolunteerInfo query = new VolunteerInfo();
            query.setUserId(user.getId());
            Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(query, PageRequest.of(0, 1));
            if (volunteerInfoPage.isEmpty()) {
                // 如果不存在，创建新的志愿者信息
                volunteerInfo = new VolunteerInfo();
                volunteerInfo.setUserId(user.getId());
                volunteerInfo.setCreateTime(new Date());
            } else {
                volunteerInfo = volunteerInfoPage.getContent().get(0);
            }

            // 更新志愿者信息
            volunteerInfo.setRealName(volunteerDTO.getRealName());
            volunteerInfo.setGender(volunteerDTO.getGender());
            volunteerInfo.setBirthDate(volunteerDTO.getBirthDate());
            volunteerInfo.setRegion(volunteerDTO.getRegion());
            volunteerInfo.setSkills(volunteerDTO.getSkills());
            volunteerInfo.setUpdateTime(new Date());

            VolunteerInfo updatedVolunteerInfo;
            if (volunteerInfo.getId() == null) {
                updatedVolunteerInfo = volunteerInfoService.insert(volunteerInfo);
            } else {
                updatedVolunteerInfo = volunteerInfoService.update(volunteerInfo);
            }

            // 构建返回DTO
            VolunteerDTO resultDTO = VolunteerDTO.fromUserAndVolunteerInfo(updatedUser, updatedVolunteerInfo);

            return ResponseEntity.ok(ApiResponse.success(resultDTO, "更新个人资料成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(500, "更新个人资料失败: " + e.getMessage()));
        }
    }

    /**
     * 上传头像
     *
     * @param file 头像文件
     * @return 上传结果
     */
    @PostMapping("/avatar")
    public ResponseEntity<ApiResponse<String>> uploadAvatar(@RequestParam("file") MultipartFile file) {

        // 检查文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "文件为空"));
        }

        try {
            // 生成文件名
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

            // 保存文件
            String uploadDir = "uploads/avatars/";
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            Path filePath = uploadPath.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);

            // 返回头像路径
            String avatarPath = "/uploads/avatars/" + fileName;

            return ResponseEntity.ok(ApiResponse.success(avatarPath, "上传头像成功"));
        } catch (IOException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "上传头像失败: " + e.getMessage()));
        }
    }

    /**
     * 获取当前登录用户的ID
     *
     * @return 当前用户ID
     */
    private Long getCurrentUserId() {
        // 从 SecurityContextHolder 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 获取用户名
            String username = authentication.getName();
            // 通过用户名查询用户信息
            User user = userMapper.findByUsername(username);
            if (user != null) {
                return user.getId();
            }
        }
        // 如果无法获取用户信息，抛出异常
        throw new RuntimeException("未能获取当前用户信息，请确保用户已登录");
    }
}
